package com.android.readcard.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.readcard.R;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.dialog.MyUsualyDialog;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.android.readcard.global.ConstantsValue;
import com.android.readcard.global.PrefReadCardTools;
import com.android.readcard.inter.UpLoadListener;
import com.android.readcard.read.DjlmConnectUtils;
import com.android.readcard.read.OtgMiNiUtils;
import com.android.readcard.utils.GlobReadCardUtils;
import com.android.readcard.utils.ToastUtils;
import com.kaeridcard.client.BtReaderClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cc.lotuscard.LotusCardDriver;

/**
 * 在读卡界面注册EventBus获取数据
 *
 * @Override protected boolean isRegisterEventBus() {
 * return true;
 * }
 * @Override protected void receiveEvent(Event event) {
 * switch (event.getCode()) {
 * case EventCodes.EventReadCardCode.A: // 读卡
 * smSmzj.setEnabled(true);
 * dialog.show();
 * BackReadInfo data = (BackReadInfo) event.getData();
 * ReadCardInfo readInfo = data.getInfo();
 * CardData cardData = data.getCardData();
 * String chuanma = data.getChuanma();
 * Log.e("项目异常receiveEvent", "------ReadCardInfo------" + readInfo.toString());
 * Log.e("项目异常receiveEvent", "------CardData------" + cardData.toString());
 * Log.e("项目异常receiveEvent", "------chuanma------" + chuanma);
 * <p>
 * // 上传身份信息获取经办人数据
 * SubReadCardDataUtils.getJingBanRenData(readInfo, cardData, chuanma, new SubReadDataListener() {
 * @Override public void subPhotoSuc(String needJb, String photoUrl) {
 * setReadData(photoUrl, readInfo); // 处理读卡数据
 * getFacePrem(); // // 读卡成功后获取活体检测授权
 * }
 * @Override public void subErr(String msg) {
 * if (dialog != null) {
 * dialog.dismiss();
 * }
 * ToastUtils.showShortToast(ShiMingActivity.this, msg);
 * }
 * });
 * break;
 * }
 * }
 * 2018.11.13
 */

public class ReadCardActivity extends AppCompatActivity implements View.OnClickListener, UpLoadListener {

    private TextView btnBule;
    private TextView btnNfc;
    private TextView btnOtg;
    private TextView btnDismess;

    private String bluetoothName = ""; // 蓝牙名称
    private String bluetoothType = "";

    private LinearLayout llNamelist;
    private MyUsualyDialog myUsualyDialog;
    private BtReaderClient mClient;

    private UsbDevice m_LotusCardDevice = null;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private UsbManager m_UsbManager = null;
    private final int m_nVID = 1306;
    private final int m_nPID = 20763;
    private String m_strDeviceNode;
    private UsbInterface m_LotusCardInterface = null;
    private UsbDeviceConnection m_LotusCardDeviceConnection = null;
    private LotusCardDriver mLotusCardDriver;
    private Boolean m_bCanUseUsbHostApi = true;
    private OtgMiNiUtils otgMiNiUtils;
    private DjlmConnectUtils djlmConnectUtils;
    private String otgUrl;

    private BluetoothAdapter ba;
    private int index = 0;
    private boolean isPrem = false;

    // otg初始化
    @SuppressLint("NewApi")
    private Boolean SetUsbCallBack() {
        Boolean bResult = false;
        PendingIntent pendingIntent;
        pendingIntent = PendingIntent.getBroadcast(ReadCardActivity.this, 0, new Intent(
                ACTION_USB_PERMISSION), 0);
        m_UsbManager = (UsbManager) getSystemService(USB_SERVICE);
        if (null == m_UsbManager)
            return bResult;

        HashMap<String, UsbDevice> deviceList = m_UsbManager.getDeviceList();
        if (!deviceList.isEmpty()) {
            for (UsbDevice device : deviceList.values()) {
                if ((m_nVID == device.getVendorId())
                        && (m_nPID == device.getProductId())) {
                    m_LotusCardDevice = device;
                    m_strDeviceNode = m_LotusCardDevice.getDeviceName();
                    break;
                }
            }
        }
        if (null == m_LotusCardDevice)
            return bResult;
        m_LotusCardInterface = m_LotusCardDevice.getInterface(0);
        if (null == m_LotusCardInterface)
            return bResult;
        if (false == m_UsbManager.hasPermission(m_LotusCardDevice)) {
            m_UsbManager.requestPermission(m_LotusCardDevice, pendingIntent);
        }
        UsbDeviceConnection conn = null;
        if (m_UsbManager.hasPermission(m_LotusCardDevice)) {
            conn = m_UsbManager.openDevice(m_LotusCardDevice);
        }

        if (null == conn)
            return bResult;

        if (conn.claimInterface(m_LotusCardInterface, true)) {
            m_LotusCardDeviceConnection = conn;
        } else {
            conn.close();
        }
        if (null == m_LotusCardDeviceConnection)
            return bResult;
        // 把上面获取的对性设置到接口中用于回调操作
        LotusCardDriver.m_UsbDeviceConnection = m_LotusCardDeviceConnection;
        if (m_LotusCardInterface.getEndpoint(1) != null) {
            LotusCardDriver.m_OutEndpoint = m_LotusCardInterface.getEndpoint(1);
        }
        if (m_LotusCardInterface.getEndpoint(0) != null) {
            LotusCardDriver.m_InEndpoint = m_LotusCardInterface.getEndpoint(0);
        }
        bResult = true;
        return bResult;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_readcard);
        initView();
        stopRead();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断当前系统是不是Android6.0
            requestRuntimePermissions(PERMISSIONS_STORAGE, new PermissionListener() {
                @Override
                public void granted() {
                    isPrem = true;
                    //权限申请通过
                    initData();
                }

                @Override
                public void denied(List<String> deniedList) {
                    //权限申请未通过
                    ToastUtils.showShortToast(ReadCardActivity.this, "没有文件读写权限,请检查是否打开！");
                }
            });
        } else {
            isPrem = true;
            //权限申请通过
            initData();
        }
    }

    private void initData() {
        ba = BluetoothAdapter.getDefaultAdapter();
        GlobReadCardUtils.copyLibFile(ReadCardActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (btnBule != null) {
            btnBule.setEnabled(true);
        }
    }

    @Override
    public void onClick(View v) {
        int btnId = v.getId();
        if (btnId == R.id.btn_dismess) {
            finish();
        } else {
            if (btnId == R.id.btn_bule) {
                if (isPrem) {
                    btnBule.setEnabled(false);
                    startActivity(new Intent(ReadCardActivity.this, BleActivity.class));
                    finish();
                } else {
                    ToastUtils.showShortToast(ReadCardActivity.this, "没有文件读写权限,请检查是否打开！");
                }

            } else if (btnId == R.id.btn_nfc) {
                if (isPrem) {
                    index = 1;
                    btnNfc.setEnabled(false);
                    bluetoothName = "NFC";
                    llNamelist.setVisibility(View.GONE); // 隐藏界面
                    myUsualyDialog.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            djlmOrNfc("", "", null, true);
                        }
                    }).start();
                } else {
                    ToastUtils.showShortToast(ReadCardActivity.this, "没有文件读写权限,请检查是否打开！");
                }

            } else if (btnId == R.id.btn_otg) {
                if (isPrem) {
                    index = 2;
                    btnOtg.setEnabled(false);
                    bluetoothName = "OTG";
                    otgUrl = PrefReadCardTools.getString(ReadCardActivity.this, ConstantsValue.OTGserverIp, "60.13.188.194");
                    llNamelist.setVisibility(View.GONE); // 隐藏界面
                    myUsualyDialog.show();

                    mLotusCardDriver = new LotusCardDriver();// OTG
                    m_bCanUseUsbHostApi = SetUsbCallBack(); // OTG

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            otgMiNiUtils = new OtgMiNiUtils(otgUrl, bluetoothType, mLotusCardDriver,
                                    bluetoothName, ReadCardActivity.this);
                            otgMiNiUtils.OnTestIdListener();
                        }
                    }).start();
                } else {
                    ToastUtils.showShortToast(ReadCardActivity.this, "请检查应用的存储和位置权限,并允许！");
                }
            }
        }
    }

    private void initView() {
        llNamelist = findViewById(R.id.ll_namelist);

        btnBule = findViewById(R.id.btn_bule);
        btnNfc = findViewById(R.id.btn_nfc);
        btnOtg = findViewById(R.id.btn_otg);
        btnDismess = findViewById(R.id.btn_dismess);

        btnOtg.setVisibility(View.VISIBLE);
        btnBule.setOnClickListener(this);
        btnNfc.setOnClickListener(this);
        btnOtg.setOnClickListener(this);
        btnDismess.setOnClickListener(this);

        myUsualyDialog = new MyUsualyDialog(ReadCardActivity.this, R.layout.wait_item);
        myUsualyDialog.setCanceledOnTouchOutside(true);
        myUsualyDialog.setCancelable(false);

    }

    private void djlmOrNfc(String bleAddress, String bleName, BluetoothDevice remoteDevice, boolean flag) {

        mClient = new BtReaderClient(ReadCardActivity.this);
        mClient.setCallBack(GlobReadCardUtils.mCallback);
        djlmConnectUtils = new DjlmConnectUtils(ReadCardActivity.this, bluetoothType, ba,
                remoteDevice, bleName, bleAddress, bluetoothName, ReadCardActivity.this);
        djlmConnectUtils.connect(mClient, flag);
    }

    @Override
    public void onSucUpLoad(ReadCardInfo info, CardData cardData, String chuanma) {
        Log.e("项目异常读卡", "------onSucUpLoad------" + info.toString());
        // 读卡成功
        setReadData(info, cardData, chuanma);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String err = (String) msg.obj;
                if (!TextUtils.isEmpty(err)) {
                    ToastUtils.showShortToast(ReadCardActivity.this, err);
                }
                if (myUsualyDialog != null) {
                    myUsualyDialog.dismiss();
                }
                finish();
            }
        }
    };

    @Override
    public void onErrUpLoad(int bleType, String err) {
        closeReadCard(bleType);
        Message message = new Message();
        message.what = 1;
        message.obj = err;
        mHandler.sendMessage(message); // 发送消息,弹出错误提示并关闭界面
    }

    /**
     * 设置数据,EventBus传递回去
     *
     * @param info
     * @param cardData
     */
    private void setReadData(ReadCardInfo info, CardData cardData, String chuanma) {
        if (myUsualyDialog != null) {
            myUsualyDialog.dismiss();
        }
        BackReadInfo backReadInfo = new BackReadInfo();
        backReadInfo.setInfo(info);
        backReadInfo.setCardData(cardData);
        backReadInfo.setChuanma(chuanma);
        Event<BackReadInfo> event = new Event<>(EventCodes.EventReadCardCode.A, backReadInfo);
        EventBusUtil.sendEvent(event);
        finish();
    }

    /**
     * 终止读卡
     *
     * @param bleType
     */
    private void closeReadCard(int bleType) {
        if (bleType == 1) {
            djlmConnectUtils.stopConnect();
        } else {
            btnBule.setEnabled(true);
            btnNfc.setEnabled(true);
            btnOtg.setEnabled(true);
        }
    }

    /**
     * 监听返回键和弹窗消失事件
     */
    public void stopRead() {
        myUsualyDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                finish();
            }
        });
        myUsualyDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                closeReadCard(index);
                myUsualyDialog.dismiss();
                return true;
            }
        });
    }

    //**************************************权限申请********************************************
    private static PermissionListener mListener;

    public interface PermissionListener {
        void granted();

        void denied(List<String> deniedList);
    }

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    /**
     * 申请权限
     */
    public void requestRuntimePermissions(
            String[] permissions, PermissionListener listener) {
        mListener = listener;
//        List<String> permissionList = new ArrayList<>();
//        // 遍历每一个申请的权限，把没有通过的权限放在集合中
//        for (String permission : permissions) {
//            if (ContextCompat.checkSelfPermission(ReadCardActivity.this, permission) !=
//                    PackageManager.PERMISSION_GRANTED) {
//                permissionList.add(permission);
//            } else {
//                mListener.granted();
//            }
//        }
        // 申请权限
        ActivityCompat.requestPermissions(ReadCardActivity.this,
                PERMISSIONS_STORAGE, 1);
    }

    /**
     * 申请后的处理
     */
    @Override
    public void onRequestPermissionsResult(
            int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            List<String> deniedList = new ArrayList<>();
            // 遍历所有申请的权限，把被拒绝的权限放入集合
            for (int i = 0; i < grantResults.length; i++) {
                int grantResult = grantResults[i];
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    mListener.granted();
                } else {
                    deniedList.add(permissions[i]);
                }
            }
            if (!deniedList.isEmpty()) {
                mListener.denied(deniedList);
            }
        }
    }

}
